<!-- 采购单的退货结算 -->
<template>
	<view style="p-b-140">
		<hx-navbar ref="hxnb" :config="config" @onBack="onBack" @clickBtn="clickBtn"></hx-navbar>
		<view class="time-view" @click="() => timeShow = true">
			{{ bill.businessTime }}
		</view>
		<view class="form-view">
			<view class="form-item"
				@click="onLink('/pages/application/pages/personnel/supplier/supplier?type=thjs&page=thjs')">
				<view class="label">
					供应商
				</view>
				<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
					<text>{{ bill.comegoName }}</text>
				</view>
			</view>
			<view class="form-item">
				<view class="flex col-item">
					<view class="label">
						前欠
					</view>
					<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
						{{ bill.debtTotal || 0 }}
					</view>
				</view>
				<view class="flex col-item">
					<view class="label">
						累欠
					</view>
					<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
						{{ bill.debtCurrent }}
					</view>
				</view>
			</view>
			<view class="form-item"
				@click="onOther">
				<view class="label blue">
					其他
				</view>
				<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
					<text v-if="bill.amountOtherList" v-for="(item, index) in bill.amountOtherList" :key="index">
						{{ item.amountItemName }},
					</text>
				</view>
			</view>
			<view class="form-item">
				<view class="flex col-item"
					@click="onAccount">
					<view class="label">
						账户
					</view>
					<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
						<text v-if="bill.accountPaidList" v-for="(item, index) in bill.accountPaidList" :key="index">
							{{ item.accountName }},
						</text>
					</view>
				</view>
				<view class="flex col-item">
					<view class="label w-250 blue">
						付款金额
					</view>
					<view class="w-140" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
						<text v-if="bill.accountPaidList">{{ totalAmountPaid }}</text>
					</view>
				</view>

			</view>
			<view class="form-item">
				<view class="label">
					备注
				</view>
				<view class="value" :class="bill.auditState && !bill.isCancel ? 'c-99' : ''">
					<u--input placeholder="" border="none" v-model="bill.remarks"></u--input>
				</view>
			</view>
			<view class="form-item" v-if="isExpand">
				<view class="flex col-item">
					<view class="label blue">
						货运
					</view>
					<view class="value">
						<u--input placeholder="" border="none"></u--input>
					</view>
				</view>
				<view class="flex col-item">
					<view class="label">
						运费
					</view>
					<view class="value">
						<u--input placeholder="" border="none">
						</u--input>
						<u-icon name="photo" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="form-item" v-if="isExpand">
				<view class="label">
					货运单
				</view>
				<view class="value">
					<u--input placeholder="" border="none"></u--input>
				</view>
			</view>

			<view class="expand flex">
				<view class="flex expand-item" @click="setExpand">
					<template v-if="isExpand">
						<u-icon name="arrow-up" color="#ccc" size="16"></u-icon>
						<view class="text">
							收起
						</view>
					</template>
					<template v-else>
						<u-icon name="arrow-down" color="#ccc" size="16"></u-icon>
						<view class="text">
							展开
						</view>
					</template>
				</view>
				<view class="flex expand-item">
					<u-icon name="attach" color="#ccc" size="16"></u-icon>
					<view class="text">
						附件
					</view>
				</view>
			</view>
		</view>
		<!-- 时间选择器 -->
		<u-datetime-picker @cancel="() => { timeShow = false }" :show="timeShow" v-model="time" mode="datetime"
			@confirm="timeConfirm"></u-datetime-picker>
		<!-- 已选择的产品列表 -->
		<c-list :likeList="likeList" :listData="listData" @procureLink="procureLink" @link="onLink"></c-list>
		<!-- 底部悬浮 -->
    <view v-if="bill.auditState == null && bill.isDraft == null">
      <foot
        v-if="bill.id == null"
        @save="onSaveFun"
        :footData="footData"
        source="cgdreturn"
        type="cgdreturn"
      ></foot>
      <foot
        v-if="bill.id != null"
        @save="onUpdateFun"
        :footData="footData"
        source="cgdreturn"
        type="cgdreturn"
      ></foot>
    </view>
		<!-- auditState : true ; isDraft : false-->
		<examine v-else-if="!bill.auditState && !bill.isDraft" @save="onSaveExamine" :footData="footData" source="cgdreturn"
			type="cgdreturn"></examine>
		<cancel v-if="bill.auditState && !bill.isCancel" @save="() => { cancelShow = true }" :footData="footData"
			source="cgdreturn" type="cgdreturn">
		</cancel>
		<u-popup class="u-pop" :show="modalShow" :round="10" mode="center" :closeOnClickOverlay="false">
			<view class="popup-view">
				<view class="title" style="line-height: 282rpx;">
					您确定要保存吗?
				</view>
				<view class="bot-view flex flex-sa">
					<view class="btn" @click="() => { modalShow = false }">
						取消
					</view>
					<view class="btn" @click="toRoter()">
						不保存
					</view>
					<view class="btn" @click="onSaveFun()">
						保存
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup class="u-pop" :show="cancelShow" :round="10" mode="center" :closeOnClickOverlay="false">
			<view class="popup-view">
				<view class="title" style="line-height: 282rpx;">
					您确定要作废当前单据吗?
				</view>
				<view class="bot-view flex flex-sa">
					<view class="btn" @click="() => { cancelShow = false }">
						取消
					</view>
					<view class="btn" @click="onSaveCancel()">
						确认
					</view>
				</view>
			</view>
		</u-popup>
    <delete-data
      @close="
        () => {
          deleteShow = false;
        }
      "
      :show="deleteShow"
      :id="bill.id"
      @delectDatalist="delectDatalist"
    ></delete-data>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
import { date } from '@/utils/util.js'
import foot from '../components/footer.vue'
import examine from '../components/examine.vue'
import cancel from '../components/cancel.vue'
import cList from '../components/list.vue'
import deleteData from "../components/delete-data.vue";
import { getSupplierLastRemainDebtTotal } from "@/apis/bill/purchase";
import { initAddBill, addData, updateViewBillAndDetailsByBillId, audit, purchaseCancel,deleteById ,updateData} from "@/apis/bill/purchase-return"
export default {
	name: '',
	components: {
		foot,
		cList,
		examine,
		cancel,
		deleteData
	},
	computed: {
		totalAmountPaid() {
			if (!this.bill.accountPaidList) {
				return 0
			} else {
				return this.bill.accountPaidList.reduce((total, item) => Number(total) + Number(item.amountPaid), 0);
			}
		},

	},
	data() {
		return {
      // 删除按钮弹窗
      deleteShow: false,
			// 控制模态窗显示 退出按钮
			modalShow: false,
			// 作废按钮
			cancelShow: false,
			isExpand: false,
			time: Number(new Date()),
			timeShow: false,
			config: {
				title: "退货结算",
				color: "#ffffff",
				//背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
				backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          // {
          //   key: "btn1",
          //   icon: "&#xe646;",
          //   position: "left",
          // },
          {
            key: "btn2",
            txt: "",
            icon: "&#xed34;",
            // position: "left",
          },
        ],
				backTabPage: '',
				backPage: '',
				navigateBack: null
			},
			// 产品数组
			listData: [],
			bill: {
				"id": null,
				"gid": null,
				"billNo": "JHD202308020001",
				"businessTime": "2023-08-02 23:47:11",
				"shopId": "1666657492773502976",
				"shopName": "总店",
				"comegoId": "",
				"comegoName": "",
				"amountPayable": 0,
				"amountPaid": 0,
				"debtCurrent": 279972,
				"debtTotal": 279972,
				"debtThisTime": null,
				"totalQuantity": null,
				"totalPrice": null,
				"writeOffAmount": null,
				"cancelTime": null,
				"cancelUserId": null,
				"cancelUserName": null,
				"cancelCause": null,
				"auditTime": null,
				"auditUserId": null,
				"auditUserName": null,
				"isCancel": null,
				"isSettle": null,
				"auditState": null,
				"handUserId": "1666657492773502977",
				"handUserName": "老板",
				"createUserId": null,
				"createUserName": null,
				"remarks": null,
				"tenantId": null,
				"transporter": null,
				"amountOtherList": null,
				"accountPaidList": null
			},
			product: {},
			footData: {
				piecesCount: 0,
				totalPrice: 0
			},
			likeList:[]
		}
	},
	onLoad(opt) {
    this.likeList = this.$getPageParams("djRowItem")?.likeList || [
			{ label: "宽幅/克重", check: true },
			{ label: "规格", check: true },
			{ label: "缸号", check: true },
			{ label: "批号", check: true },
			{ label: "辅编号/名称", check: true },
		]
    if (this.$ls.get("cgdreturnInformation")?.bill) {
      this.bill = this.$ls.get("cgdreturnInformation").bill;
      this.bill.auditState = null;
      this.bill.isDraft = null;
    } else {
      if (opt && opt.type == "details") {
        this.getDetailsData(opt.id);
      } else {
        this.initAddBills();
      }
    }
		// ---- 采购单逻辑
		// this.product = this.$ls.get('cgdreturnInformation')

		uni.$on('settlementComego', data => {
			this.bill.comegoName = data.name
			this.bill.comegoId = data.id
			this.obtainArrears()
		})
		uni.$on('on-receipt-other-expenses', data => {
			this.bill.amountOtherList = data
		})
		uni.$on('receiptSelectBank', data => {
			this.bill.accountPaidList = data
		})
	},
	onShow() {
		this.getPageData()
	},
	methods: {
    onUpdateFun() {
      this.modalShow = false;
      if (this.listData.length <= 0) {
        this.$refs.uToast.show({
          type: "erroror",
          title: "",
          message: "不允许保存空单",
        });
        return;
      }
      let data = {
        bill: this.bill,
        billDetailList: this.listData,
      };
      updateData(data).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.$refs.uToast.show({
          type: "success",
          title: "",
          message: "保存成功",
          // complete() {
          // 	uni.switchTab({
          // 		url: '/pages/application/index'
          // 	})
          // }
        });
        this.bill = data.bill;
        this.bill.auditState = false;
        this.bill.isDraft = false;
				let item = {
					supplier: {
						name: data.comegoName,
						id: data.comegoId
					}, // 客户数据
					productInformation: data.billDetailList, // 产品数据
				}
				this.$ls.set('cgdreturnInformation', item)
        this.getPageData();
      });
    },
    // 删除销售单
    delectDatalist() {
      let _this = this;
      _this.deleteShow = false;
      uni.showModal({
        content: "您确认删除当前单据吗?",
        success: function (res) {
          if (res.confirm) {
            deleteById(_this.bill.id).then((res) => {
              if (!res.flag) return;
              _this.$refs.uToast.show({
                type: "success",
                title: "",
                message: "删除成功",
                complete() {
                  uni.switchTab({
                    url: "/pages/application/index",
                  });
                },
              });
            });
          } else if (res.cancel) {
          }
        },
      });
    },
    clickBtn(item) {
      if (item.key === "btn1") {
        this.printShow = true;
      } else if (item.key === "btn2") {
        this.deleteShow = !this.deleteShow;
      }
    },
		// 返回到主页面
		toRoter() {
			uni.switchTab({
				url: '/pages/application/index'
			});
		},
		// 左上角返回按钮
		onBack() {
      if (this.bill.auditState == null && this.bill.isDraft == null) {
        if (this.listData.length <= 0) {
          uni.switchTab({
            url: "/pages/application/index",
          });
          return;
        } else {
          this.modalShow = true;
        }
      } else {
        uni.switchTab({
          url: "/pages/application/index",
        });
      }
		},
		getDetailsData(id) {
			updateViewBillAndDetailsByBillId(id).then((res) => {
				if (!res.flag) return;
				const data = res.data || {};
				this.bill = data.bill
				let item = {
					supplier: {
						name: data.comegoName,
						id: data.comegoId
					}, // 客户数据
					productInformation: data.billDetailList, // 产品数据
				}
				this.$ls.set('cgdreturnInformation', item)
				this.getPageData()
			});
		},
		// 审核
		onSaveExamine() {
			let _this = this
			uni.showModal({
				content: '您确认审核当前单据吗?',
				success: function (res) {
					if (res.confirm) {
						audit(_this.bill.id).then((res) => {
							if (!res.flag) return;
							const data = res.data || {};
							_this.$refs.uToast.show({
								type: 'success',
								title: '',
								message: "审核成功",
							})
							_this.getDetailsData(_this.bill.id)
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});

		},
		// 作废
		onSaveCancel(show) {
			this.cancelShow = false
			purchaseCancel(this.bill.id).then((res) => {
				if (!res.flag) return;
				const data = res.data || {};
				this.$refs.uToast.show({
					type: 'success',
					title: '',
					message: "作废成功",
					complete() {
						uni.switchTab({
							url: '/pages/application/index'
						});
					}
				})
			});
		},
		// 展开
		setExpand() {
			this.isExpand = !this.isExpand;
		},
		timeConfirm() {
			this.bill.businessTime = date('Y-m-d H:i:s', this.time)
			this.obtainArrears()
			this.timeShow = false
		},
		// 获取当前欠款
		obtainArrears() {
			getSupplierLastRemainDebtTotal({
				businessTime: this.bill.businessTime,
				supplierId: this.bill.comegoId
			}).then((res) => {
				if (!res.flag) return;
				const data = res.data || 0;
				this.bill.debtTotal = data
			});
		},
		// 获取存储的数据来更新页面
		getPageData() {
			// ---- 销售单逻辑
			this.product = this.$ls.get('cgdreturnInformation')
			this.footData.piecesCount = 0
			this.footData.totalPrice = 0
			if (this.product) {
				for (let index = 0; index < this.product.productInformation.length; index++) {
					if (this.product.productInformation[index].piecesCount) {
						this.footData.piecesCount = this.footData.piecesCount + Number(this.product.productInformation[index].piecesCount)
					}
					if (this.product.productInformation[index].totalPrice) {
						this.footData.totalPrice = this.footData.totalPrice + Number(this.product.productInformation[index].totalPrice)
					}
				}
				// console.log("this.footData",this.footData);
				this.listData = this.product.productInformation
				// 更新当前累欠
				this.countTirednessMoney()
			}
		},
		// 计算累欠金额
		countTirednessMoney() {
			// 收款
			let totalAmountPaid = 0
			this.bill.debtCurrent = 0
			if (!this.bill.accountPaidList) {
				totalAmountPaid = 0
			} else {
				totalAmountPaid = this.bill.accountPaidList.reduce((total, item) => Number(total) + Number(item.amountPaid), 0);
			}

			this.bill.debtCurrent = this.footData.totalPrice - totalAmountPaid


		},
    // 列表查看详情
		procureLink(item, index) {
      let likeList = this.$getPageParams("djRowItem")?.likeList || [
        { label: "宽幅/克重", check: true },
        { label: "规格", check: true },
        { label: "缸号", check: true },
        { label: "批号", check: true },
        { label: "辅编号/名称", check: true },
      ];
			this.$setPageParams('djRowItem', {
				list: item,
				info: {
					isEcho: true,
					index: index
				},
				likeList: likeList,
			})
      // 把当前的销售单数据存进去
      let dataItem = this.$ls.get("cgdreturnInformation");
      dataItem.bill = this.bill;
      this.$ls.set("cgdreturnInformation", dataItem);
			uni.navigateTo({
				url: `/pages/application/pages/cloth/customer-product-billing/index?source=cgdreturn`
			})
		},
		onSaveFun() {
			this.modalShow = false;
			if (this.listData.length <= 0) {
				this.$refs.uToast.show({
					type: 'error',
					title: '',
					message: "不允许保存空单",
				})
				return
			}
			let data = {
				bill: this.bill,
				billDetailList: this.listData
			}
			addData(data).then((res) => {
				if (!res.flag) return;
				console.log("res", res.data);
				const data = res.data || {};
				this.$refs.uToast.show({
					type: 'success',
					title: '默认主题',
					message: "保存成功",
				})
				this.bill = data.bill
				let item = {
					supplier: {
						name: data.comegoName,
						id: data.comegoId
					}, // 客户数据
					productInformation: data.billDetailList, // 产品数据
				}
				this.$ls.set('cgdreturnInformation', item)
				// this.getDetailsData(data.bill.id)
				this.getPageData()
			});
		},
		// 获取当前订单和时间
		initAddBills() {
			initAddBill().then((res) => {
				if (!res.flag) return;
				const data = res.data || {};
				this.bill = Object.assign(this.bill, data.bill)
				// 获取当前供应商的名称
				this.bill.comegoName = this.product.supplier.name
				this.bill.comegoId = this.product.supplier.id
				this.obtainArrears()
				// 更新当前累欠
				this.countTirednessMoney()
			});
		},
    // 跳转其他费用
    onOther() {
      if (this.bill.auditState && !this.bill.isCancel) {
        return;
      }
      uni.navigateTo({
        url:
          "/pages/application/pages/finance/accounts-receivable-payable/components/select-other-expenses?data=" +
          encodeURIComponent(JSON.stringify(this.bill.amountOtherList || [])),
      });
    },
		// 跳转账户
		onAccount() {
      if (this.bill.auditState && !this.bill.isCancel) {
        return;
      }
      uni.navigateTo({
        url:
          "/pages/application/pages/finance/accounts-receivable-payable/components/select-bank?data=" +
          encodeURIComponent(JSON.stringify(this.bill.accountPaidList || [])),
      });
		},
		// 跳转地址
		onLink(route) {
			this.$Router.push({
				path: route,
			});
		}
	},
	mounted() { },
	beforeDestroy() {
		uni.$off("settlementComego");
		uni.$off("on-receipt-other-expenses");
		uni.$off("receiptSelectBank");
	},
}
</script>

<style lang="scss" scoped>
.time-view {
	background: linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246));
	text-align: center;
	padding: 20rpx 0 40rpx;
	color: rgba(255, 255, 255, 0.6);
}

.expand {
	.expand-item {
		padding: 20rpx 0;
		position: relative;
		flex: 1;
		justify-content: center;

		&:first-child::after {
			content: "";
			position: absolute;
			width: 1rpx;
			height: 80%;
			background-color: #ccc;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}

		.text {
			color: #999;
			padding-left: 10rpx;
		}
	}
}

.form-view {
	background: #fff;
	overflow: hidden;

	.form-item {
		display: flex;
		border-bottom: 1rpx solid #ddd;
		padding: 24rpx 40rpx;
		align-items: center;
		font-size: 30rpx;

		.label {
			color: #999;
			flex: 1;
			text-align: right;
			padding-right: 18rpx;
		}

		.close-view {
			// padding: 0 20rpx;
		}

		.value {
			flex: 6;
			display: flex;
		}

		.category {
			justify-content: space-between;
		}

		.col-item {
			flex: 1;

			.value {
				flex: 2.4;
			}
		}
	}
}
</style>